package org.srtc.infopub.worker;

import java.util.Hashtable;
import java.util.Map;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQMapMessage;

public class Publisher
	{

		protected int MAX_DELTA_PERCENT = 1;
		protected Map<String, Double> LAST_PRICES = new Hashtable<String, Double>();
		protected static int count = 10;
		protected static int total;

		protected static String brokerURL = "failover:tcp://localhost:61618";
		protected static transient ConnectionFactory factory;
		protected transient Connection connection;
		protected transient Session session;
		protected transient MessageProducer producer;

		public Publisher() throws JMSException
			{
				factory = new ActiveMQConnectionFactory(brokerURL);
				connection = factory.createConnection();
				try
					{
						connection.start();
					} catch (JMSException jmse)
					{
						connection.close();
						throw jmse;
					}
				session = connection.createSession(false,
						Session.AUTO_ACKNOWLEDGE);
				producer = session.createProducer(null);
				producer.setTimeToLive(20000);
			}

		public void close() throws JMSException
			{
				if (connection != null)
					{
						connection.close();
					}
			}

		protected void sendMessage(String[] stocks) throws JMSException
			{
				String info_category="001";
				Destination destination = session
						.createTopic("WORK_DATA");
				
				
				int  gzmbh=1;
				double zxc=Math.random();
				double qxc=Math.random();
			    double qj=Math.random()*10;
			    double cg=Math.random()*10;
			    double mchd=Math.random()*10;

			    
				MapMessage message = session.createMapMessage();
				
				message.setInt("001.001.001.", gzmbh);
				message.setDouble("001.001.002.", zxc);
				message.setDouble("001.001.003.", qxc);
				message.setDouble("001.001.004.", qj);
				message.setDouble("001.001.005.", cg);
				message.setDouble("001.001.006.", mchd);
				
				System.out.println("Sending: "
						+ ((ActiveMQMapMessage) message).getContentMap()
						+ " on destination: " + destination);
				producer.send(destination, message);
			}
		
		public static void main(String[] args) throws JMSException
			{
				Publisher publisher = new Publisher();
				boolean flag=true;
				while (flag)
					{
						for (int i = 0; i < count; i++)
							{
								publisher.sendMessage(args);
							}
						total += count;
						System.out.println("Published '" + count + "' of '"
								+ total + "' price messages");
						try
							{
								Thread.sleep(1000);
							} catch (InterruptedException x)
							{
							}
					}
				publisher.close();
			}

	}